<!DOCTYPE html>
<html>
	<head>
		<title>优惠券添加/编辑</title>
		<meta charset="utf-8">
		<meta name="viewport"
			content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- 所有的 css & js 资源 -->
		<link rel="stylesheet" href="https://unpkg.com/element-ui@2.13.0/lib/theme-chalk/index.css">
		<link rel="stylesheet" href="../../static/sa.css">
		<script src="https://unpkg.com/vue@2.6.10/dist/vue.js"></script>
		<script src="https://unpkg.com/element-ui@2.13.0/lib/index.js"></script>
		<script src="https://unpkg.com/http-vue-loader@1.4.2/src/httpVueLoader.js"></script>
		<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.min.js"></script>
		<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
		<script src="../../static/sa.js"></script>
		<style>
			.coupon-form {
				max-width: 800px;
				margin: 0 auto;
				padding: 20px;
			}
			.form-section {
				background: #fff;
				border-radius: 8px;
				padding: 24px;
				margin-bottom: 20px;
				box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
			}
			.section-title {
				font-size: 16px;
				font-weight: 500;
				color: #303133;
				margin-bottom: 20px;
				padding-bottom: 10px;
				border-bottom: 2px solid #409EFF;
			}
			.form-row {
				display: flex;
				gap: 20px;
				margin-bottom: 20px;
			}
			.form-col {
				flex: 1;
			}
			.form-col-half {
				flex: 0 0 48%;
			}
			.tips {
				color: #909399;
				font-size: 12px;
				margin-top: 5px;
				line-height: 1.4;
			}
			.coupon-preview {
				background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
				border-radius: 12px;
				padding: 20px;
				color: white;
				position: relative;
				overflow: hidden;
			}
			.coupon-preview::before {
				content: '';
				position: absolute;
				top: 50%;
				right: -10px;
				width: 20px;
				height: 20px;
				background: #f5f5f5;
				border-radius: 50%;
				transform: translateY(-50%);
			}
			.coupon-preview::after {
				content: '';
				position: absolute;
				top: 50%;
				left: -10px;
				width: 20px;
				height: 20px;
				background: #f5f5f5;
				border-radius: 50%;
				transform: translateY(-50%);
			}
			.coupon-amount {
				font-size: 32px;
				font-weight: bold;
				margin-bottom: 8px;
			}
			.coupon-name {
				font-size: 16px;
				margin-bottom: 12px;
			}
			.coupon-info {
				font-size: 12px;
				opacity: 0.9;
			}
			.action-buttons {
				text-align: center;
				padding: 20px 0;
			}
		</style>
	</head>
	<body>
		<div class="vue-box" style="display: none;" :style="'display: block;'">
			<div class="coupon-form">
				<div class="form-section">
					<div class="section-title">
						<i class="el-icon-tickets"></i>
						优惠券{{ isAdd ? '添加' : '编辑' }}
					</div>

					<el-form v-if="m" label-width="120px" :rules="rules" ref="form" :model="m" label-position="top">
						<!-- 基本信息 -->
						<div class="form-row">
							<div class="form-col">
								<el-form-item label="优惠券名称" prop="name">
									<el-input v-model="m.name" placeholder="请输入优惠券名称" maxlength="50" show-word-limit>
										<template slot="prepend">
											<i class="el-icon-price-tag"></i>
										</template>
									</el-input>
									<div class="tips">建议使用简洁明了的名称，如"新用户专享券"、"满减优惠券"等</div>
								</el-form-item>
							</div>
						</div>

						<!-- 优惠设置 -->
						<div class="form-row">
							<div class="form-col-half">
								<el-form-item label="优惠类型" prop="type">
									<el-select v-model="m.type" placeholder="请选择优惠类型" style="width: 100%">
										<el-option label="满减券" value="amount" icon="el-icon-money"></el-option>
										<el-option label="折扣券" value="discount" icon="el-icon-discount"></el-option>
									</el-select>
									<div class="tips">满减券：减免固定金额；折扣券：按比例折扣</div>
								</el-form-item>
							</div>
							<div class="form-col-half">
								<el-form-item :label="m.type === 'discount' ? '折扣比例' : '优惠金额'" prop="amount">
									<el-input-number v-model="m.amount"
										:precision="m.type === 'discount' ? 1 : 2"
										:step="m.type === 'discount' ? 0.1 : 1"
										:min="m.type === 'discount' ? 0.1 : 0.01"
										:max="m.type === 'discount' ? 9.9 : 99999"
										controls-position="right"
										:placeholder="m.type === 'discount' ? '请输入折扣比例' : '请输入优惠金额'"
										style="width: 100%">
									</el-input-number>
									<div class="tips">{{ m.type === 'discount' ? '折扣比例，如8.5表示8.5折' : '优惠金额，单位：元' }}</div>
								</el-form-item>
							</div>
						</div>

						<!-- 使用条件 -->
						<div class="form-row">
							<div class="form-col-half">
								<el-form-item label="最低消费" prop="minOrderAmount">
									<el-input-number v-model="m.minOrderAmount" :precision="2" :step="10" :min="0" :max="99999"
										controls-position="right" placeholder="请输入最低消费金额" style="width: 100%">
									</el-input-number>
									<div class="tips">设置为0表示无门槛使用</div>
								</el-form-item>
							</div>
							<div class="form-col-half">
								<el-form-item label="每人限领" prop="limitPerUser">
									<el-input-number v-model="m.limitPerUser" :step="1" :min="1" :max="999"
										controls-position="right" placeholder="每人限领数量" style="width: 100%">
									</el-input-number>
									<div class="tips">每个用户最多可领取的数量</div>
								</el-form-item>
							</div>
						</div>

						<!-- 发放设置 -->
						<div class="form-row">
							<div class="form-col-half">
								<el-form-item label="发放总量" prop="totalQuantity">
									<el-input-number v-model="m.totalQuantity" :step="1" :min="1" :max="999999"
										controls-position="right" placeholder="发放总量" style="width: 100%">
									</el-input-number>
									<div class="tips">此优惠券的总发放数量</div>
								</el-form-item>
							</div>
							<div class="form-col-half">
								<el-form-item label="有效期设置">
									<el-radio-group v-model="m.validityType">
										<el-radio label="fixed">固定时间</el-radio>
										<el-radio label="relative">相对时间</el-radio>
									</el-radio-group>
								</el-form-item>
							</div>
						</div>

						<!-- 有效期设置 -->
						<div class="form-row" v-if="m.validityType === 'fixed'">
							<div class="form-col">
								<el-form-item label="有效期" prop="dateRange">
									<el-date-picker v-model="dateRange" type="daterange" range-separator="至"
										start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd"
										:picker-options="pickerOptions" @change="handleDateChange" style="width: 100%">
									</el-date-picker>
									<div class="tips">设置优惠券的使用有效期</div>
								</el-form-item>
							</div>
						</div>

						<div class="form-row" v-if="m.validityType === 'relative'">
							<div class="form-col">
								<el-form-item label="有效天数" prop="validDays">
									<el-input-number v-model="m.validDays" :step="1" :min="1" :max="365"
										controls-position="right" placeholder="领取后有效天数" style="width: 200px">
									</el-input-number>
									<span style="margin-left: 10px; color: #909399;">天</span>
									<div class="tips">用户领取后多少天内有效</div>
								</el-form-item>
							</div>
						</div>

						<!-- 使用说明 -->
						<div class="form-row">
							<div class="form-col">
								<el-form-item label="使用说明">
									<el-input type="textarea" v-model="m.description"
										placeholder="请输入优惠券使用说明..." :rows="3" maxlength="200" show-word-limit>
									</el-input>
									<div class="tips">详细说明优惠券的使用规则和注意事项</div>
								</el-form-item>
							</div>
						</div>
					</el-form>
				</div>

				<!-- 优惠券预览 -->
				<div class="form-section" v-if="m.name">
					<div class="section-title">
						<i class="el-icon-view"></i>
						优惠券预览
					</div>
					<div class="coupon-preview">
						<div class="coupon-amount">
							{{ m.type === 'discount' ? m.amount + '折' : '￥' + m.amount }}
						</div>
						<div class="coupon-name">{{ m.name || '优惠券名称' }}</div>
						<div class="coupon-info">
							<div>{{ m.minOrderAmount > 0 ? '满￥' + m.minOrderAmount + '可用' : '无门槛使用' }}</div>
							<div v-if="m.validityType === 'fixed' && m.startDate && m.endDate">
								有效期：{{ m.startDate }} 至 {{ m.endDate }}
							</div>
							<div v-if="m.validityType === 'relative' && m.validDays">
								领取后{{ m.validDays }}天内有效
							</div>
						</div>
					</div>
				</div>

				<!-- 操作按钮 -->
				<div class="action-buttons">
					<el-button type="primary" icon="el-icon-check" @click="ok" size="medium"
						:loading="loading">{{ isAdd ? '确认添加' : '确认修改' }}</el-button>
					<el-button @click="resetForm" icon="el-icon-refresh" size="medium"
						style="margin-left: 10px;" v-if="isAdd">重置</el-button>
					<el-button @click="sa.closeCurrIframe()" icon="el-icon-close" size="medium"
						style="margin-left: 10px;">取消</el-button>
				</div>
			</div>
		</div>
		<script>
			new Vue({
				el: '.vue-box',
				data: {
					isAdd: true,
					loading: false,
					dateRange: [],
					pickerOptions: {
						disabledDate(time) {
							return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
						}
					},
					m: {
						id: '',
						name: '',
						type: 'amount', // 优惠类型：amount-满减券，discount-折扣券
						amount: 0,
						startDate: '',
						endDate: '',
						minOrderAmount: 0,
						limitPerUser: 1, // 每人限领数量
						totalQuantity: 100, // 发放总量
						validityType: 'fixed', // 有效期类型：fixed-固定时间，relative-相对时间
						validDays: 30, // 相对时间的有效天数
						description: '' // 使用说明
					},
					rules: {
						name: [{
								required: true,
								message: '请输入优惠券名称',
								trigger: 'blur'
							},
							{
								min: 2,
								max: 50,
								message: '长度在 2 到 50 个字符',
								trigger: 'blur'
							}
						],
						type: [{
							required: true,
							message: '请选择优惠类型',
							trigger: 'change'
						}],
						amount: [{
								required: true,
								message: '请输入优惠金额或折扣比例',
								trigger: 'blur'
							},
							{
								validator: (rule, value, callback) => {
									if (this.m.type === 'discount') {
										if (value <= 0 || value >= 10) {
											callback(new Error('折扣比例必须在0.1-9.9之间'));
										}
									} else {
										if (value <= 0) {
											callback(new Error('优惠金额必须大于0'));
										}
									}
									callback();
								},
								trigger: 'blur'
							}
						],
						minOrderAmount: [{
							type: 'number',
							min: 0,
							message: '最低消费不能小于0',
							trigger: 'blur'
						}],
						limitPerUser: [{
							required: true,
							type: 'number',
							min: 1,
							message: '每人限领数量至少为1',
							trigger: 'blur'
						}],
						totalQuantity: [{
							required: true,
							type: 'number',
							min: 1,
							message: '发放总量至少为1',
							trigger: 'blur'
						}],
						validDays: [{
							validator: (rule, value, callback) => {
								if (this.m.validityType === 'relative') {
									if (!value || value < 1 || value > 365) {
										callback(new Error('有效天数必须在1-365之间'));
									}
								}
								callback();
							},
							trigger: 'blur'
						}],
						dateRange: [{
							validator: (rule, value, callback) => {
								if (this.m.validityType === 'fixed') {
									if (!this.dateRange || this.dateRange.length !== 2) {
										callback(new Error('请选择有效期'));
									}
								}
								callback();
							},
							trigger: 'change'
						}]
					}
				},
				created() {
					// 获取编辑id和数据
					var id = sa.p('id');
					var couponData = sa.p('couponData');
					this.isAdd = (id == null || id == '' || id == '-1');
					if (!this.isAdd && couponData) {
						this.m = Object.assign({}, this.m, couponData);
						// 设置日期范围
						if (this.m.startDate && this.m.endDate) {
							this.dateRange = [this.m.startDate, this.m.endDate];
						}
					}
				},
				methods: {
					// 日期改变时
					handleDateChange: function(val) {
						if (val) {
							this.m.startDate = val[0];
							this.m.endDate = val[1];
						} else {
							this.m.startDate = '';
							this.m.endDate = '';
						}
					},

					// 验证优惠券设置的合理性
					validateCouponSettings() {
						// 折扣券的特殊验证
						if (this.m.type === 'discount') {
							if (this.m.amount >= 10) {
								this.$message.warning('折扣比例不能大于等于10折，请检查设置');
								return false;
							}
							// 折扣券的最低消费应该合理
							if (this.m.minOrderAmount > 0 && this.m.minOrderAmount < 10) {
								this.$message.warning('折扣券的最低消费建议设置为10元以上');
								return false;
							}
						}

						// 满减券的特殊验证
						if (this.m.type === 'amount') {
							if (this.m.minOrderAmount > 0 && this.m.amount >= this.m.minOrderAmount) {
								this.$message.warning('优惠金额不应该大于等于最低消费金额');
								return false;
							}
						}

						// 发放数量验证
						if (this.m.totalQuantity < this.m.limitPerUser) {
							this.$message.warning('发放总量不能小于每人限领数量');
							return false;
						}

						return true;
					},

					// 生成优惠券预览数据
					generatePreviewData() {
						return {
							name: this.m.name || '优惠券名称',
							type: this.m.type,
							amount: this.m.amount,
							minOrderAmount: this.m.minOrderAmount,
							validityType: this.m.validityType,
							startDate: this.m.startDate,
							endDate: this.m.endDate,
							validDays: this.m.validDays
						};
					},
					// 提交数据
					ok: function() {
						this.$refs.form.validate((valid) => {
							if (!valid) return;

							// 验证有效期设置
							if (this.m.validityType === 'fixed') {
								if (!this.m.startDate || !this.m.endDate) {
									return this.$message.error('请选择有效期');
								}
							} else if (this.m.validityType === 'relative') {
								if (!this.m.validDays || this.m.validDays < 1) {
									return this.$message.error('请设置有效天数');
								}
							}

							// 验证优惠券设置的合理性
							if (!this.validateCouponSettings()) {
								return;
							}

							this.loading = true;

							// 数据预处理和验证
							const submitData = {
								name: this.m.name.trim(),
								type: this.m.type,
								amount: parseFloat(this.m.amount),
								min_order_amount: parseFloat(this.m.minOrderAmount),
								limit_per_user: parseInt(this.m.limitPerUser),
								total_quantity: parseInt(this.m.totalQuantity),
								validity_type: this.m.validityType,
								description: this.m.description ? this.m.description.trim() : ''
							};

							// 根据有效期类型设置不同字段
							if (this.m.validityType === 'fixed') {
								submitData.start_date = this.m.startDate;
								submitData.end_date = this.m.endDate;
							} else {
								submitData.valid_days = parseInt(this.m.validDays);
							}

							// 如果是编辑模式，添加ID
							if (!this.isAdd && this.m.id) {
								submitData.id = this.m.id;
							}

							console.log('提交的优惠券数据:', submitData);

							// 验证必填字段
							if (!submitData.name) {
								this.loading = false;
								return this.$message.error('请输入优惠券名称');
							}

							if (isNaN(submitData.amount) || submitData.amount <= 0) {
								this.loading = false;
								return this.$message.error('请输入正确的优惠金额或折扣比例');
							}

							if (this.m.validityType === 'fixed') {
								if (!submitData.start_date || !submitData.end_date) {
									this.loading = false;
									return this.$message.error('请选择有效期');
								}
								if (submitData.end_date < submitData.start_date) {
									this.loading = false;
									return this.$message.error('结束日期不能早于开始日期');
								}
							}

							const apiUrl = this.isAdd ?
								'http://localhost:8080/coupon/addCoupon' :
								'http://localhost:8080/coupon/updateCoupon';

							$.ajax({
								url: apiUrl,
								type: 'POST',
								contentType: 'application/json;charset=UTF-8',
								data: JSON.stringify(submitData),
								success: function(res) {
									this.loading = false;
									if (res.code === 200) {
										this.$message.success(this.isAdd ? '添加成功' : '修改成功');
										// 刷新父页面的列表
										if (window.parent && window.parent.app) {
											window.parent.app.f5();
										}
										// 如果是添加模式，重置表单
										if (this.isAdd) {
											this.resetForm();
										}
									} else {
										this.$message.error(res.message || (this.isAdd ? '添加失败' : '修改失败'));
									}
								}.bind(this),
								error: function(xhr, status, error) {
									this.loading = false;
									console.error('提交失败:', error);
									this.$message.error('网络错误，请稍后重试');
								}.bind(this)
							});
						});
					},
					// 重置表单
					resetForm() {
						this.m = {
							id: '',
							name: '',
							type: 'amount',
							amount: 0,
							startDate: '',
							endDate: '',
							minOrderAmount: 0,
							limitPerUser: 1,
							totalQuantity: 100,
							validityType: 'fixed',
							validDays: 30,
							description: ''
						};
						this.dateRange = [];
						this.$nextTick(() => {
							this.$refs.form.resetFields();
						});
					}
				},

				// 监听器
				watch: {
					// 监听优惠类型变化，调整默认值
					'm.type': function(newType) {
						if (newType === 'discount') {
							// 折扣券默认8.5折
							if (this.m.amount === 0 || this.m.amount > 10) {
								this.m.amount = 8.5;
							}
						} else {
							// 满减券默认10元
							if (this.m.amount === 0 || this.m.amount < 1) {
								this.m.amount = 10;
							}
						}
					},

					// 监听有效期类型变化
					'm.validityType': function(newType) {
						if (newType === 'relative') {
							// 清空固定时间设置
							this.dateRange = [];
							this.m.startDate = '';
							this.m.endDate = '';
						}
					}
				}
			})
		</script>
	</body>
</html>